package com.neu.cloudfactory.controler;

import com.neu.cloudfactory.bean.Capacity.Capactity;
import com.neu.cloudfactory.repository.CapactityRepository;
import com.neu.cloudfactory.service.Capactityservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
public class CapactityControler implements Capactityservice {
    @Autowired
    CapactityRepository capactityRepository;

    @RequestMapping("/capactity/findAllByEquipmentidAndFactoryid/{equipmentid}/{factoryid}")
    public List<Capactity> findAllByEquipmentidAndFactoryid(@PathVariable("equipmentid") Integer equipmentid,@PathVariable("factoryid") Integer factoryid){
        return capactityRepository.findAllByEquipmentidAndFactoryid(equipmentid, factoryid);
    }
    @RequestMapping("/capactity/findAllByEquipmentid/{equipmentid}")
    public List<Capactity> findAllByEquipmentid(@PathVariable("equipmentid") Integer equipmentid){
        return capactityRepository.findAllByEquipmentid(equipmentid);
    }

    @RequestMapping("/capactity/add")
    public String add(@RequestBody Capactity capactity){
        boolean complete = false;
        try {
            Optional<Capactity> tmp = capactityRepository.findByEquipmentidAndFactoryidAndProductid(capactity.getEquipmentid(),capactity.getFactoryid(),capactity.getProductid());
            if(tmp.isPresent()){
                capactity.setId(tmp.get().getId());
            }
            capactity = capactityRepository.save(capactity);
            complete = capactity.getId()!=null;
        }catch (Exception e){

        }
        return complete?"success":"failed";
    }
    @RequestMapping("/capactity/update")
    public String update(@RequestBody Capactity capactity){
        boolean complete = false;
        try {
            capactity = capactityRepository.save(capactity);
            complete = capactity.getId()!=null;
        }catch (Exception e){

        }
        return complete?"success":"failed";
    }

    @RequestMapping("/capactity/deleteById/{id}")
    public String deleteById(@PathVariable("id") Integer id){
        boolean complete = false;
        try{
            capactityRepository.deleteById(id);
            complete = true;
        }catch (Exception e){

        }
        return complete?"success":"failed";
    }
}
